package com.cuitrip.business.pay;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.PayBusiness;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.pay.model.AdyenInfo;
import com.cuitrip.business.pay.model.Card;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.PayPopupWindow;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.service.R;
import com.cuitrip.util.NetworkUtil;
import com.cuitrip.util.text.CardExpiryTextWatcher;
import com.cuitrip.util.text.CreditCardTextWatcher;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.LogHelper;
import com.lab.utils.Utils;

import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by MiJack on 2015/11/30.
 */
public class CreditCardPayActivity extends CustomUiFragmentActivity implements View.OnClickListener {
    public static final String KEY_CREDITCARD_TYPE = "KEY_CREDITCARD_TYPE";
    public static final String KEY_MONEY_COUNT = "KEY_MONEY_COUNT";
    public static final String KEY_ORDERITEM="key_orderitem";
    public static final String KEY_COUPONID="key_couponId";
    //正式key:10001|BC4213C3F858A3A2E2FB7167274ED854A133EFA55C593512EF6CA56EF8595BD891CC449B391D59F77ABDFEB6742A21E962ADC1CA1DE5199721AC4BAB1C0768FA60AEC7EAE7B6A880B3A10F290BA7AB563EA0C0EBB10A82332CD2F160E804750E134DB56AA78701D1C7CD0B31149AF221014D8CE9D117E59604C77AD31E8F26DA801817EDDB0E6797D31D7DC459181D69BF2D167A1FC42CD81258EBFDE852040EAD86F76A4FA0D6CD4EB8020C077F9E137D4EE959964AB5813DF10E73A6BFB4DF7AF0C9FFEED4D5347714D639A00745701EBAC39952755ED3606F46B0FA047AAEA9512F99B0A62567D561C2AC38339A8BB54EE0CAE4E1821F98B4E1209FB0E8FB
    //测试&预发:10001|C2B358BA50C28E742C6EC966F415D929E8ED91DE7350892FE3F9B844DFDC80BF50F6A4B5AE7BE34FB0E005D0AC307021BB35F7FD72F1C3F9C7F10DFEA7E2C744932D84C793C882BA9E7C22122525A6F6C91575A5076C1B6B2BE781E3DDF09753F745CD1476580ED365A2DD57E72876FB6C90889F3868C97637822770DA86814D705C0CDFA881F934E9423F323EC2158EB1CA60316D90F2C74585EADD7FF22EEC3AEEC0B248699914C2F2F639A3208B8327623D87504667E6B03B325C225136A1FFCBDEEAB5154035C3167445F78CC56881A8433E63E2A96618685FA436F41CECB372863B4C4F4C72CC689B1D65E2FF349F243A52CB0292C3EA186E9D0C9C5D9F
    private final String pubKey = "10001|BC4213C3F858A3A2E2FB7167274ED854A133EFA55C593512EF6CA56EF8595BD891CC449B391D59F77ABDFEB6742A21E962ADC1CA1DE5199721AC4BAB1C0768FA60AEC7EAE7B6A880B3A10F290BA7AB563EA0C0EBB10A82332CD2F160E804750E134DB56AA78701D1C7CD0B31149AF221014D8CE9D117E59604C77AD31E8F26DA801817EDDB0E6797D31D7DC459181D69BF2D167A1FC42CD81258EBFDE852040EAD86F76A4FA0D6CD4EB8020C077F9E137D4EE959964AB5813DF10E73A6BFB4DF7AF0C9FFEED4D5347714D639A00745701EBAC39952755ED3606F46B0FA047AAEA9512F99B0A62567D561C2AC38339A8BB54EE0CAE4E1821F98B4E1209FB0E8FB";
    String tag = this.getClass().getName();
    CreditCard creditCard;
    @Bind(R.id.card_logo)
    ImageView logoView;
    @Bind(R.id.card_tip)
    TextView logoTip;
    @Bind(R.id.button)
    Button button;
    @Bind(R.id.editCardNumber)
    EditText editCardNumber;
    @Bind(R.id.editCardHolder)
    EditText editCardHolder;
    @Bind(R.id.editCardExpiry)
    TextView editCardExpiry;
    @Bind(R.id.editCVC)
    EditText editCVC;
    PayPopupWindow payPopupWindow;
    private String moneyType;
    private String moneyCount;
    private OrderItem item;
    private String encrypted;
    private String oid;
    private String channel;
    private String couponId;
    private View root;

    public static void startActivity(Context context, int type, String moneyCount,OrderItem item,String couponId) {
        Bundle args = new Bundle();
        args.putInt(KEY_CREDITCARD_TYPE, type);
        args.putString(KEY_MONEY_COUNT, moneyCount);
        args.putSerializable(KEY_ORDERITEM, item);
        args.putSerializable(KEY_COUPONID, couponId);
        Intent intent = new Intent(context, CreditCardPayActivity.class);
        intent.putExtras(args);
        Jumper.launchActivity(context, intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        root = LayoutInflater.from(this).inflate(R.layout.fragment_credit_card_pay, null);
        onCreate(savedInstanceState, root);
        ButterKnife.bind(this, root);
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras!=null) {
            int anInt = extras.getInt(KEY_CREDITCARD_TYPE);
            switch (anInt) {
                case 1:
                    creditCard = CreditCard.VISA;
                    channel="visa";
                    break;

                case 2:
                    creditCard=CreditCard.MASTER_CARD;
                    channel="wc";
                    break;

                default:
                    throw new IllegalArgumentException("");
            }
           // moneyType = extras.getString(KEY_MONEY_TYPE);
            moneyCount = extras.getString(KEY_MONEY_COUNT);
            //oid=extras.getString(KEY_OID);
            item = (OrderItem) extras.getSerializable(KEY_ORDERITEM);
            oid=item.getOid();
            moneyType=item.getPayCurrency();
            couponId=extras.getString(KEY_COUPONID);
        }

        editCVC.setHint(creditCard.cvcHintRes);
        button.setText(getString(R.string.pay) + " " + moneyType + " " + moneyCount);
        logoView.setImageResource(creditCard.logoRes);
        logoTip.setText(creditCard.contentRes);
        CreditCardTextWatcher textWatcher = new CreditCardTextWatcher();
        editCardNumber.addTextChangedListener(textWatcher);
        InputFilter.LengthFilter lengthFilter = new InputFilter.LengthFilter(19 + 4);
        InputFilter[] filters = new InputFilter[]{lengthFilter};
        editCardExpiry.addTextChangedListener(new CardExpiryTextWatcher());
        editCardExpiry.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5), new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int i = 0; i < source.length(); i++) {
                    if (!Character.isDigit(source.charAt(i)) && '/' != source.charAt(i)) {
                        return "";
                    }
                }
                return source.subSequence(start, end);
            }
        }});
        editCardNumber.setFilters(filters);
        editCVC.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button) {
            if (check()) {
                ChoiceDialog choiceDialog = ChoiceDialog.getInstance();
                choiceDialog.setDialogTitle(getResources().getString(R.string.pay_confirm,moneyType,moneyCount));
                choiceDialog.setDialogMessageVisibility(false);
                choiceDialog.setDialogCoupleStyleSetting(
                        getResources().getString(R.string.operation_yes),
                        getResources().getString(R.string.operation_cancel), new ChoiceDialog.DialogStyleCoupleCallback() {
                            @Override
                            public boolean onPositiveButtonClick() {
                                pay();
                                return false;
                            }

                            @Override
                            public boolean onNegativeButtonClick() {
                                return false;
                            }
                        });
                showDialogFragment(choiceDialog);
            }
        }
    }


    private boolean check() {
        String cardNumber = editCardNumber.getText().toString();
        String cardHolder = editCardHolder.getText().toString();
        String cardExpiry = editCardExpiry.getText().toString();
        String cardCVC = editCVC.getText().toString();
        if (cardNumber.length() < 16 + 3) {
            Utils.shakeView(editCardNumber);
            return false;
        }
        if (TextUtils.isEmpty(cardHolder)) {
            Utils.shakeView(editCardHolder);
            return false;
        }
        if (cardExpiry.length() != 1 + 4) {
            Utils.shakeView(editCardExpiry);
            return false;
        }
        if (cardCVC.length() < 3) {
            Utils.shakeView(editCVC);
            return false;
        }
        return true;
    }

    private void pay() {
        showLoading();
        StringBuilder sb = new StringBuilder();
        String source = editCardNumber.getText().toString();
        for (int i = 0; i < source.length(); i++) {
            char c = source.charAt(i);
            if (Character.isDigit(c)) {
                sb.append(c);
            }
        }
        String cardNumber = sb.toString();
        String cardHolder = editCardHolder.getText().toString();
        String cardExpiry = editCardExpiry.getText().toString();
        String cardCVC = editCVC.getText().toString();
        String year = "20" + cardExpiry.substring(3);
        String month = cardExpiry.substring(0, 2);
        Card card=new Card.Builder(new Date()).
                number(cardNumber).
                cvc(cardCVC).
                expiryMonth(month)
                .expiryYear(year)
                .holderName(cardHolder)
                .build();
        PayEncrypter enc;
        try {
            enc = new PayEncrypter(pubKey);
            encrypted=enc.encrypt(card.toString());
            LogHelper.i(tag, enc.encrypt(card.toString()));
        } catch (EncrypterException e) {
            LogHelper.w(tag, e.getMessage());
        }
        PayBusiness.requestPayWithAdyen(new ApiProxy(new IProxyCallback() {

            private AdyenInfo info;

            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                final CtApiResponse response = (CtApiResponse) result.getData();
                if (result != null) {//解析json
                    if (response.result instanceof AdyenInfo) {
                        info = (AdyenInfo) response.result;
                    }
                    if (response.result instanceof JSONObject) {
                        try {
                            info = JSON.parseObject(response.result.toString(), AdyenInfo.class);
                        } catch (Exception e) {
                            info = null;
                        }
                    }
                    if (info != null){
                        if (response.code==CtResponseCode.RESULT_OK&&info.getResultCode().equalsIgnoreCase("Authorised")){
                            //支付成功
                            payPopupWindow.setState(PayPopupWindow.STATE.SUCCESS);
                            return false;
                        }
                        if (!TextUtils.isEmpty(info.getRefusalReason())){
                            payPopupWindow.setFail(info.getRefusalReason());
                            return false;
                        }
                    }
                    if (response.result instanceof  String && !TextUtils.isEmpty(response.result.toString())){
                        OrderBusiness.getOrderInfo(new ApiProxy(new IProxyCallback() {
                            @Override
                            public boolean onProxyResult(ProxyResult<?> result) {
                                CtApiResponse ctApiResponse= (CtApiResponse) result.getData();
                                if(ctApiResponse.result!=null && ctApiResponse.code==CtResponseCode.RESULT_OK){
                                    if(ctApiResponse.result instanceof OrderItem){
                                        OrderItem item= (OrderItem) ctApiResponse.result;
                                        if (item.getStatus() > OrderItem.STATUS_WAIT_PAY) {
                                            payPopupWindow.setState(PayPopupWindow.STATE.SUCCESS);
                                        }
                                    }
                                }else{
                                    payPopupWindow.setFail(response.result.toString());
                                    return false;
                                }
                                return false;
                            }
                        }),oid);
                    }
                    if (response.msg instanceof  String && !TextUtils.isEmpty(response.msg.toString())){
                        payPopupWindow.setFail(response.msg.toString());
                        return false;
                    }
                }
                payPopupWindow.setFail(getString(R.string.pay_operation_pay_feedback_fail));
                return false;
            }
        }), oid, channel, NetworkUtil.getIPAddress(), moneyType, encrypted, couponId);

        //显示popupwindow
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View content = inflater.inflate(R.layout.popup_window_pay, null);
        payPopupWindow = new PayPopupWindow(content);
        hideLoading();
        payPopupWindow.showAtLocation(root, Gravity.BOTTOM, 0, 0);
        payPopupWindow.setState(PayPopupWindow.STATE.LOADING);
        payPopupWindow.setCall(new PayPopupWindow.CallBack() {
            @Override
            public void call() {
                if(payPopupWindow.getState().equals(PayPopupWindow.STATE.SUCCESS)&& item!=null){
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            String email = "";
                            CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                            if (userInfo != null) {
                                email = userInfo.getEmail();
                            }
                            //OrderFormActivity.start(CreditCardPayActivity.this, item);
                            PaySucActivity.start(CreditCardPayActivity.this,email,item,3);
                            finish();
                        }
                    }, 1000);


                }
            }
        });

    }



    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.payment);
        config.mTopbarStyle = CustomUiConfig.BarStyle.WHITE_STYLE;
        return config;
    }


    enum CreditCard {
        VISA(R.drawable.visa_logo, R.string.account_visa_pay_desc, R.string.account_visa_attribute_validation),
        MASTER_CARD(R.drawable.mastercard_logo, R.string.account_mastercard_pay_desc, R.string.account_mastercard_attribute_validation);
        int logoRes;
        int contentRes;
        int cvcHintRes;

        CreditCard(int logoRes, int contentRes, int cvcHintRes) {
            this.logoRes = logoRes;
            this.contentRes = contentRes;
            this.cvcHintRes = cvcHintRes;
        }
    }
}
